###############################################################################
#drafted by Jeremy VanDerWal ( jjvanderwal@gmail.com ... www.jjvanderwal.com )
#GNU General Public License .. feel free to use / distribute ... no warranties
################################################################################
### define species inputs
timeline='Post_decline' # or 'Pre_decline'

occur.file = paste('/home/jc148322/frog_declines/',timeline,'.csv',sep='')#the file with your species code, lat and longs
bkgd.file = '/home/jc148322/frog_declines/bkgd.csv'#the file with all occurrence records, lats and longs
wd=paste('/home/jc148322/frog_declines/SDM2/',timeline,'/',sep='');dir.create(wd)# your work directory eg."/home/jc148322/SDM/Random_bkgd/"; 
dir.create(wd); setwd(wd) #define and set the working directory
################################################################################
source('/home/jc148322/scripts/libraries/cool_functions.r')
library(SDMTools)
climate.dir='/home/jc165798/Climate/CIAS/AWT/250m/baseline.76to05/bioclim/'
maxent.jar = "/home/jc165798/working/NARP_birds/maxent.jar" #define the location of the maxent.jar file
#define the species of interest

###prepare the data
clim.vars=paste('bioclim_',sprintf('%02i',c(1:19)),sep='')
for (clim.var in clim.vars){ cat(clim.var,'\n')
	tasc=read.asc.gz(paste(climate.dir,clim.var,'.asc.gz',sep=''))
	assign(clim.var,tasc)
}

setwd(wd)

bkgd=read.csv(bkgd.file,as.is=TRUE); bkgd$Species='bkgd'
bkgd = bkgd[,1:3]
colnames(bkgd)=c('spp','lat','long')

occur = read.csv(occur.file,as.is=TRUE) #read in the occur file
occur = occur[,1:3]
colnames(occur)=c('spp','lat','long')
occur = unique(na.omit(occur)) #remove any missing data and keep on unique data

for (clim.var in clim.vars) { cat(clim.var,'\n') #cycle through each of hte climate variables
	occur[,clim.var] = extract.data(cbind(occur$long,occur$lat), get(clim.var)) #append the climate data
	bkgd[,clim.var] = extract.data(cbind(bkgd$long,bkgd$lat), get(clim.var)) #append the climate data	
}
occur = unique(na.omit(occur)) #remove any missing data and keep on unique data
bkgd=unique(na.omit(bkgd))

write.csv(bkgd,'bkgd.csv',row.names=FALSE) #write out your target group background

species=unique(occur$spp)

###cycle through each species and submit jobs to be modelled

for (spp in species) { cat(spp,'\n')
	counter=1
	contrib=0
	while(min(contrib)<5){
		if (counter==1) {toccur = occur[occur$spp==spp,] #get the observations for the species
			tbkgd=bkgd
		
		}else{
			while (!file.exists(paste(spp.dir,'output/',spp,'.lambdas',sep=''))) system('sleep 30\n')
			if (file.exists(paste(spp.dir,'output/',spp,'.lambdas',sep=''))) {system('sleep 10\n')
				contrib=read.csv(paste(spp.dir,'output/maxentResults.csv',sep=''),as.is=TRUE)
				contrib=contrib[,grep('contribution',colnames(contrib))]
				colnames(contrib)=gsub('.contribution','',colnames(contrib))
				contrib=contrib[,which(contrib>0)]
				contrib=contrib[,which(contrib>min(contrib))]
				clim.vars=colnames(contrib)
				
				toccur = occur[occur$spp==spp,]
				toccur=cbind(toccur[,1:3],toccur[,clim.vars])
				tbkgd=cbind(bkgd[,1:3],bkgd[,clim.vars])
			}
		}
		var.dir=gsub('bioclim_','',clim.vars)
		var.dir=paste('bioclim.',paste(var.dir,collapse='.'),sep='')
		
		spp.dir = paste(wd,'models/',spp,'/',var.dir,'/',sep='') #define the species directory
		dir.create(paste(spp.dir,'output',sep=''),recursive=TRUE) #create the species directory
		write.csv(toccur,paste(spp.dir,'occur.csv',sep=''),row.names=FALSE) #write out the file
		write.csv(tbkgd,paste(spp.dir,'bkgd.csv',sep=''),row.names=FALSE) #write out the file
		
		#create the shell script which will run the modelling jobs
		zz = file(paste(spp.dir,'01.',spp,'.model.sh',sep=''),'w') #create the shell script to run the maxent model
			cat('#!/bin/bash\n',file=zz)
			cat('cd ',spp.dir,'\n',sep='',file=zz)
			cat('source /etc/profile.d/modules.sh\n',file=zz) 
			cat('module load java\n',file=zz)
			#cat('java -mx2048m -jar ',maxent.jar,' -e bkgd.csv -s occur.csv -o output nothreshold nowarnings novisible replicates=10 nooutputgrids -r -a \n',sep="",file=zz) #run maxent bootstrapped to get robust model statistics
			#cat('cp -af output/maxentResults.csv output/maxentResults.crossvalide.csv\n',file=zz) #copy the maxent results file so that it is not overwritten
			cat('java -mx2048m -jar ',maxent.jar,' -e bkgd.csv -s occur.csv -o output nothreshold outputgrids plots nowarnings  responsecurves jackknife novisible nowriteclampgrid nowritemess writeplotdata -P -J -r -a \n',sep="",file=zz) #run a full model to get the best parameterized model for projecting
		close(zz)
		setwd(spp.dir); system(paste('qsub -m n 01.',spp,'.model.sh',sep='')); #submit the script
		counter=counter+1
		}
}






















